<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 6.2.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/avatar.jpg">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/avatar.jpg">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/avatar.jpg">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">

<link rel="stylesheet" href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&display=swap&subset=latin,latin-ext">
<link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">
  <link rel="stylesheet" href="/lib/pace/pace-theme-big-counter.min.css">
  <script src="/lib/pace/pace.min.js"></script>

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"raphets.github.io","root":"/","scheme":"Mist","version":"7.8.0","exturl":false,"sidebar":{"position":"right","display":"hide","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":true,"show_result":true,"style":"default"},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":false,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}}};
  </script>

  <meta name="description" content="记录一下如何将已有的sqlite数据库加密，并在Android项目中读取该加密数据库。">
<meta property="og:type" content="article">
<meta property="og:title" content="使用sqlcipher加密sqlite数据库">
<meta property="og:url" content="https://raphets.github.io/archives/8bc2eb53.html">
<meta property="og:site_name" content="尚拙">
<meta property="og:description" content="记录一下如何将已有的sqlite数据库加密，并在Android项目中读取该加密数据库。">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2024-10-15T08:37:39.000Z">
<meta property="article:modified_time" content="2025-11-28T08:30:32.961Z">
<meta property="article:author" content="John Doe">
<meta property="article:tag" content="Sqlite">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="https://raphets.github.io/archives/8bc2eb53.html">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>使用sqlcipher加密sqlite数据库 | 尚拙</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">尚拙</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">一个分享技术、学习成长的个人博客网站</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a>

  </li>
        <li class="menu-item menu-item-tool">

    <a href="/tool/" rel="section"><i class="fa fa-hammer fa-fw"></i>工具</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于</a>

  </li>
  </ul>
</nav>




</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://raphets.github.io/archives/8bc2eb53.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.jpg">
      <meta itemprop="name" content="John Doe">
      <meta itemprop="description" content="不积跬步，无以至千里；不积小流，无以成江海。">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="尚拙">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          使用sqlcipher加密sqlite数据库
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2024-10-15 16:37:39" itemprop="dateCreated datePublished" datetime="2024-10-15T16:37:39+08:00">2024-10-15</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2025-11-28 16:30:32" itemprop="dateModified" datetime="2025-11-28T16:30:32+08:00">2025-11-28</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/%E6%8A%80%E6%9C%AF%E6%96%87%E7%AB%A0/" itemprop="url" rel="index"><span itemprop="name">技术文章</span></a>
                </span>
                  ，
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/%E6%8A%80%E6%9C%AF%E6%96%87%E7%AB%A0/Android/" itemprop="url" rel="index"><span itemprop="name">Android</span></a>
                </span>
            </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <p>记录一下如何将已有的sqlite数据库加密，并在Android项目中读取该加密数据库。</p>
<span id="more"></span>

<h1 id="加密已有的数据库"><a href="#加密已有的数据库" class="headerlink" title="加密已有的数据库"></a>加密已有的数据库</h1><p>这里我直接用的一个开源的sqlite数据库浏览器。</p>
<p>官网：<a target="_blank" rel="noopener" href="https://sqlitebrowser.org/">https://sqlitebrowser.org/</a></p>
<p>GitHub地址：<a target="_blank" rel="noopener" href="https://github.com/sqlitebrowser/sqlitebrowser">https://github.com/sqlitebrowser/sqlitebrowser</a></p>
<p>使用该工具打开要加密的数据库，工具栏选择”设置加密”，可以对数据库进行加密。</p>
<p>加密方式目前可以选择SQLCipher3和SQLCipher4，具体用哪个版本需要与解密的sqlcipher版本对应。</p>
<h1 id="Android中解密数据库"><a href="#Android中解密数据库" class="headerlink" title="Android中解密数据库"></a>Android中解密数据库</h1><p>Android中解密数据库需要用到第三方库，目前有两个版本，旧版本停止维护了，推荐用新版本。</p>
<p>旧版本：<a target="_blank" rel="noopener" href="https://github.com/sqlcipher/android-database-sqlcipher">https://github.com/sqlcipher/android-database-sqlcipher</a></p>
<p>新版本：<a target="_blank" rel="noopener" href="https://github.com/sqlcipher/sqlcipher-android">https://github.com/sqlcipher/sqlcipher-android</a></p>
<p>这里我们用的是最新版本的库。</p>
<h5 id="1、添加依赖"><a href="#1、添加依赖" class="headerlink" title="1、添加依赖"></a>1、添加依赖</h5><figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">implementation &#x27;net.zetetic:sqlcipher-android:4.6.0@aar&#x27;</span><br><span class="line">implementation &#x27;androidx.sqlite:sqlite:2.2.0&#x27;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h5 id="2、手动加载so库"><a href="#2、手动加载so库" class="headerlink" title="2、手动加载so库"></a>2、手动加载so库</h5><p>使用前请手动加载so库，可以放在Application的onCreate中：</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">System.loadLibrary(&quot;sqlcipher&quot;);</span><br></pre></td></tr></table></figure>

<h5 id="3、复制数据库"><a href="#3、复制数据库" class="headerlink" title="3、复制数据库"></a>3、复制数据库</h5><p>将assets中的数据库文件复制到系统目录。</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">private static void copyDataBase(Context context)  &#123;</span><br><span class="line">        Log.i(&quot;[QDataBaseHelper]&quot;,&quot;copyDataBase start&quot;);</span><br><span class="line">        try &#123;</span><br><span class="line">            // Open your local db as the input stream</span><br><span class="line">            InputStream myInput = context.getAssets().open(DB_NAME);</span><br><span class="line">            // Path to the just created empty db</span><br><span class="line">            String outFileName = DB_PATH + DB_NAME;</span><br><span class="line">            File file = new File(outFileName);</span><br><span class="line">            if (!file.getParentFile().exists())&#123;</span><br><span class="line">                file.getParentFile().mkdirs();</span><br><span class="line">            &#125;</span><br><span class="line">            // Open the empty db as the output stream</span><br><span class="line">            OutputStream myOutput = new FileOutputStream(outFileName);</span><br><span class="line">            // transfer bytes from the inputfile to the outputfile</span><br><span class="line">            byte[] buffer = new byte[1024];</span><br><span class="line">            int length;</span><br><span class="line">            while ((length = myInput.read(buffer)) &gt; 0) &#123;</span><br><span class="line">                myOutput.write(buffer, 0, length);</span><br><span class="line">            &#125;</span><br><span class="line">            // Close the streams</span><br><span class="line">            myOutput.flush();</span><br><span class="line">            myOutput.close();</span><br><span class="line">            myInput.close();</span><br><span class="line">        &#125; catch (IOException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">            Log.i(&quot;[QDataBaseHelper]&quot;,&quot;IOException&quot;+e.toString());</span><br><span class="line">        &#125;</span><br><span class="line">        Log.i(&quot;[QDataBaseHelper]&quot;,&quot;copyDataBase complete&quot;);</span><br><span class="line">    &#125;  </span><br></pre></td></tr></table></figure>

<h5 id="4、读取数据库"><a href="#4、读取数据库" class="headerlink" title="4、读取数据库"></a>4、读取数据库</h5><blockquote>
<p>注意这里用到的SQLiteDatabase都是依赖库的类。</p>
</blockquote>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">import net.zetetic.database.sqlcipher.SQLiteDatabase;</span><br><span class="line"></span><br><span class="line">public static SQLiteDatabase getDataBase() &#123;</span><br><span class="line">        String password = &quot;123456&quot;;</span><br><span class="line">        if (mDataBase == null) &#123;</span><br><span class="line">            String path = DB_PATH + DB_NAME;</span><br><span class="line">            try &#123;</span><br><span class="line">                mDataBase = SQLiteDatabase.openDatabase(path,password, null, 0, null);</span><br><span class="line">            &#125; catch (Exception e) &#123;</span><br><span class="line">                e.printStackTrace();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        return mDataBase;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>

<p>成功读取数据库后，后面的操作就跟普通数据库一样了。</p>

    </div>

    
    
    

      <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/Sqlite/" rel="tag"><i class="fa fa-tag"></i> Sqlite</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/archives/c5fcb946.html" rel="prev" title="Android 通过代码获取应用签名">
      <i class="fa fa-chevron-left"></i> Android 通过代码获取应用签名
    </a></div>
      <div class="post-nav-item">
    <a href="/archives/135b95be.html" rel="next" title="软著申请指南">
      软著申请指南 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#%E5%8A%A0%E5%AF%86%E5%B7%B2%E6%9C%89%E7%9A%84%E6%95%B0%E6%8D%AE%E5%BA%93"><span class="nav-number">1.</span> <span class="nav-text">加密已有的数据库</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#Android%E4%B8%AD%E8%A7%A3%E5%AF%86%E6%95%B0%E6%8D%AE%E5%BA%93"><span class="nav-number">2.</span> <span class="nav-text">Android中解密数据库</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#1%E3%80%81%E6%B7%BB%E5%8A%A0%E4%BE%9D%E8%B5%96"><span class="nav-number">2.0.0.0.1.</span> <span class="nav-text">1、添加依赖</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#2%E3%80%81%E6%89%8B%E5%8A%A8%E5%8A%A0%E8%BD%BDso%E5%BA%93"><span class="nav-number">2.0.0.0.2.</span> <span class="nav-text">2、手动加载so库</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#3%E3%80%81%E5%A4%8D%E5%88%B6%E6%95%B0%E6%8D%AE%E5%BA%93"><span class="nav-number">2.0.0.0.3.</span> <span class="nav-text">3、复制数据库</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#4%E3%80%81%E8%AF%BB%E5%8F%96%E6%95%B0%E6%8D%AE%E5%BA%93"><span class="nav-number">2.0.0.0.4.</span> <span class="nav-text">4、读取数据库</span></a></li></ol></li></ol></li></ol></li></ol></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="John Doe"
      src="/images/avatar.jpg">
  <p class="site-author-name" itemprop="name">John Doe</p>
  <div class="site-description" itemprop="description">不积跬步，无以至千里；不积小流，无以成江海。</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">47</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">8</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">32</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2025</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">John Doe</span>
</div>

        








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/muse.js"></script>


<script src="/js/next-boot.js"></script>




  















  

  

</body>
</html>
